<template>
  <div class="layout-container">
    <!-- 顶部导航 -->
    <header class="header-container">
      <div class="header-left">
        <div class="logo-container">
          <img class="logo-img" src="@/assets/logo.png" alt="Logo" v-if="logoUrl" />
          <h1 class="logo-text">服装定制管理系统</h1>
        </div>
        <el-icon class="toggle-sidebar" @click="toggleSidebar">
          <Fold v-if="!sidebarCollapsed" />
          <Expand v-else />
        </el-icon>
      </div>
      <div class="header-right">
        <div class="theme-switch" @click="toggleTheme">
          <el-icon>
            <MoonNight v-if="isDarkMode" />
            <Sunny v-else />
          </el-icon>
        </div>
        <el-badge :is-dot="hasNotice" class="notice-badge">
          <el-icon class="notice-icon" @click="showNoticeDrawer = true">
            <Bell />
          </el-icon>
        </el-badge>
        <el-dropdown trigger="click" @command="handleCommand">
          <div class="user-info">
            <el-avatar size="small" :src="userAvatar || defaultAvatar" />
            <span class="username">{{ username }}</span>
            <el-icon><ArrowDown /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">个人中心</el-dropdown-item>
              <el-dropdown-item command="settings">系统设置</el-dropdown-item>
              <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </header>
    
    <!-- 侧边栏和主内容区 -->
    <div class="main-container">
      <!-- 侧边栏导航 -->
      <aside class="sidebar-container" :class="{ 'collapsed': sidebarCollapsed }">
        <el-scrollbar>
          <el-menu
            :default-active="activeMenu"
            :collapse="sidebarCollapsed"
            :collapse-transition="false"
            :unique-opened="true"
            router
            class="sidebar-menu">
            
            <!-- 首页 -->
            <el-menu-item index="/home">
              <el-icon><HomeFilled /></el-icon>
              <span>首页</span>
            </el-menu-item>
            
            <!-- 定制服务 -->
            <el-sub-menu index="/custom">
              <template #title>
                <el-icon><Goods /></el-icon>
                <span>定制服务</span>
              </template>
              <el-menu-item index="/custom/submit">提交定制申请</el-menu-item>
              <el-menu-item index="/custom/list">我的定制列表</el-menu-item>
            </el-sub-menu>
            
            <!-- 设计师作品 -->
            <el-sub-menu index="/design">
              <template #title>
                <el-icon><PictureFilled /></el-icon>
                <span>设计师作品</span>
              </template>
              <el-menu-item index="/design/works">作品展示</el-menu-item>
              <el-menu-item index="/design/designers">设计师列表</el-menu-item>
            </el-sub-menu>
            
            <!-- 上门预约 -->
            <el-sub-menu index="/appointment">
              <template #title>
                <el-icon><Calendar /></el-icon>
                <span>上门预约</span>
              </template>
              <el-menu-item index="/appointment/new">新建预约</el-menu-item>
              <el-menu-item index="/appointment/list">预约列表</el-menu-item>
            </el-sub-menu>
            
            <!-- 服务评价 -->
            <el-sub-menu index="/review">
              <template #title>
                <el-icon><StarFilled /></el-icon>
                <span>服务评价</span>
              </template>
              <el-menu-item index="/review/list">我的评价</el-menu-item>
              <el-menu-item index="/review/product">产品评价</el-menu-item>
              <el-menu-item index="/review/designer">设计师评价</el-menu-item>
            </el-sub-menu>
            
            <!-- 订单中心 -->
            <el-sub-menu index="/order">
              <template #title>
                <el-icon><List /></el-icon>
                <span>订单中心</span>
              </template>
              <el-menu-item index="/order/list">订单列表</el-menu-item>
              <el-menu-item index="/order/track">订单追踪</el-menu-item>
            </el-sub-menu>
            
            <!-- 用户中心 -->
            <el-menu-item index="/user">
              <el-icon><User /></el-icon>
              <span>个人中心</span>
            </el-menu-item>
            
            <!-- 设计师仪表盘 (仅设计师用户可见) -->
            <el-sub-menu index="/designer-dashboard" v-if="userRole === 'designer'">
              <template #title>
                <el-icon><DataAnalysis /></el-icon>
                <span>设计师工作台</span>
              </template>
              <el-menu-item index="/designer-dashboard/orders">待处理订单</el-menu-item>
              <el-menu-item index="/designer-dashboard/works">我的作品</el-menu-item>
              <el-menu-item index="/designer-dashboard/schedule">工作日程</el-menu-item>
              <el-menu-item index="/designer-dashboard/reviews">客户评价</el-menu-item>
            </el-sub-menu>
            
            <!-- 管理员功能 (仅管理员用户可见) -->
            <el-sub-menu index="/admin" v-if="userRole === 'admin'">
              <template #title>
                <el-icon><Setting /></el-icon>
                <span>系统管理</span>
              </template>
              <el-menu-item index="/admin/users">用户管理</el-menu-item>
              <el-menu-item index="/admin/designers">设计师管理</el-menu-item>
              <el-menu-item index="/admin/orders">订单管理</el-menu-item>
              <el-menu-item index="/admin/products">产品管理</el-menu-item>
              <el-menu-item index="/admin/materials">面料管理</el-menu-item>
              <el-menu-item index="/admin/statistics">数据统计</el-menu-item>
              <el-menu-item index="/admin/settings">系统设置</el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-scrollbar>
        
        <div class="sidebar-footer" v-if="!sidebarCollapsed">
          <div class="footer-links">
            <a href="#" @click.prevent="openHelpDialog">帮助中心</a>
            <a href="#" @click.prevent="openFeedbackDialog">意见反馈</a>
          </div>
          <div class="version-info">版本 v1.0.0</div>
        </div>
      </aside>
      
      <!-- 主内容区 -->
      <main class="content-container">
        <el-scrollbar>
          <div class="content-wrapper">
            <router-view v-slot="{ Component }">
              <transition name="fade" mode="out-in">
                <keep-alive :include="keepAlivePages">
                  <component :is="Component" />
                </keep-alive>
              </transition>
            </router-view>
          </div>
        </el-scrollbar>
      </main>
    </div>
    
    <!-- 通知抽屉 -->
    <el-drawer
      v-model="showNoticeDrawer"
      title="消息通知"
      direction="rtl"
      size="350px">
      <div class="notice-container">
        <el-tabs v-model="activeNoticeTab">
          <el-tab-pane label="未读消息" name="unread">
            <div v-if="unreadNotices.length === 0" class="empty-notice">
              <el-empty description="暂无未读消息" />
            </div>
            <div v-else class="notice-list">
              <div 
                v-for="notice in unreadNotices" 
                :key="notice.id" 
                class="notice-item"
                @click="readNotice(notice)">
                <div class="notice-title">
                  <el-tag size="small" :type="getNoticeTagType(notice.type)">
                    {{ getNoticeTypeText(notice.type) }}
                  </el-tag>
                  <span>{{ notice.title }}</span>
                </div>
                <div class="notice-content">{{ notice.content }}</div>
                <div class="notice-time">{{ notice.time }}</div>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="全部消息" name="all">
            <div v-if="allNotices.length === 0" class="empty-notice">
              <el-empty description="暂无消息" />
            </div>
            <div v-else class="notice-list">
              <div 
                v-for="notice in allNotices" 
                :key="notice.id" 
                class="notice-item"
                :class="{ 'read': notice.isRead }"
                @click="readNotice(notice)">
                <div class="notice-title">
                  <el-tag size="small" :type="getNoticeTagType(notice.type)">
                    {{ getNoticeTypeText(notice.type) }}
                  </el-tag>
                  <span>{{ notice.title }}</span>
                </div>
                <div class="notice-content">{{ notice.content }}</div>
                <div class="notice-time">{{ notice.time }}</div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-drawer>
    
    <!-- 帮助对话框 -->
    <el-dialog
      v-model="showHelpDialog"
      title="帮助中心"
      width="50%">
      <div class="help-content">
        <h3>服装定制管理系统使用指南</h3>
        <p>欢迎使用服装定制管理系统，本系统提供以下功能：</p>
        <ul>
          <li><strong>定制服务：</strong> 提交定制申请，查看定制列表</li>
          <li><strong>设计师作品：</strong> 浏览设计师作品，了解设计师信息</li>
          <li><strong>上门预约：</strong> 预约设计师上门服务</li>
          <li><strong>服务评价：</strong> 对产品和设计师进行评价</li>
          <li><strong>订单中心：</strong> 查看订单列表和追踪订单状态</li>
        </ul>
        <p>如有任何问题，请联系客服：400-123-4567</p>
      </div>
    </el-dialog>
    
    <!-- 反馈对话框 -->
    <el-dialog
      v-model="showFeedbackDialog"
      title="意见反馈"
      width="40%">
      <el-form 
        ref="feedbackFormRef"
        :model="feedbackForm"
        :rules="feedbackRules"
        label-width="80px">
        <el-form-item label="反馈类型" prop="type">
          <el-select v-model="feedbackForm.type" placeholder="请选择反馈类型" style="width: 100%">
            <el-option label="功能建议" value="feature"></el-option>
            <el-option label="界面优化" value="ui"></el-option>
            <el-option label="问题反馈" value="bug"></el-option>
            <el-option label="其他" value="other"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="反馈内容" prop="content">
          <el-input 
            v-model="feedbackForm.content"
            type="textarea"
            :rows="4"
            placeholder="请详细描述您的问题或建议">
          </el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input 
            v-model="feedbackForm.contact"
            placeholder="请留下您的联系方式，方便我们回复（选填）">
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showFeedbackDialog = false">取消</el-button>
          <el-button type="primary" @click="submitFeedback">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, inject } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  HomeFilled, 
  Goods, 
  Calendar, 
  User, 
  List, 
  Setting, 
  DataAnalysis, 
  Bell, 
  Fold, 
  Expand, 
  StarFilled, 
  PictureFilled,
  MoonNight,
  Sunny,
  ArrowDown
} from '@element-plus/icons-vue'
import defaultAvatarUrl from '@/assets/default-avatar.png'

export default {
  name: 'Layout',
  components: {
    HomeFilled, 
    Goods, 
    Calendar, 
    User, 
    List, 
    Setting, 
    DataAnalysis, 
    Bell, 
    Fold, 
    Expand, 
    StarFilled, 
    PictureFilled,
    MoonNight,
    Sunny,
    ArrowDown
  },
  setup() {
    const router = useRouter()
    const route = useRoute()
    const feedbackFormRef = ref(null)
    
    // 侧边栏状态
    const sidebarCollapsed = ref(localStorage.getItem('sidebarCollapsed') === 'true')
    const toggleSidebar = () => {
      sidebarCollapsed.value = !sidebarCollapsed.value
      localStorage.setItem('sidebarCollapsed', sidebarCollapsed.value)
    }
    
    // 主题模式
    const isDarkMode = inject('isDarkMode')
    const toggleTheme = inject('toggleDarkMode')
    
    // 用户信息
    const username = ref(localStorage.getItem('username') || '用户')
    const userRole = ref(localStorage.getItem('userRole') || 'user')
    const userAvatar = ref(localStorage.getItem('userAvatar'))
    const defaultAvatar = defaultAvatarUrl
    
    // 通知相关
    const showNoticeDrawer = ref(false)
    const activeNoticeTab = ref('unread')
    const unreadNotices = ref([])
    const allNotices = ref([])
    const hasNotice = computed(() => unreadNotices.value.length > 0)
    
    // 获取通知（模拟数据）
    const fetchNotices = () => {
      // 在实际项目中应该调用API
      setTimeout(() => {
        const mockNotices = [
          {
            id: 1,
            type: 'order',
            title: '订单已发货',
            content: '您的订单 DD202304150001 已发货，预计3-5天送达。',
            time: '2023-04-15 14:30:25',
            isRead: false
          },
          {
            id: 2,
            type: 'system',
            title: '系统公告',
            content: '系统将于2023-04-20 凌晨2:00-4:00进行升级维护，请提前做好准备。',
            time: '2023-04-14 10:15:36',
            isRead: false
          },
          {
            id: 3,
            type: 'custom',
            title: '定制申请已确认',
            content: '您的定制申请 CU202304120008 已被设计师接受，请等待后续通知。',
            time: '2023-04-12 16:42:18',
            isRead: true
          }
        ]
        
        allNotices.value = mockNotices
        unreadNotices.value = mockNotices.filter(notice => !notice.isRead)
      }, 1000)
    }
    
    // 阅读通知
    const readNotice = (notice) => {
      // 在实际项目中应该调用API
      notice.isRead = true
      unreadNotices.value = unreadNotices.value.filter(n => n.id !== notice.id)
      ElMessage.success('已标记为已读')
    }
    
    // 获取通知类型文本
    const getNoticeTypeText = (type) => {
      const typeMap = {
        system: '系统公告',
        order: '订单消息',
        custom: '定制服务',
        appointment: '预约服务'
      }
      return typeMap[type] || '其他消息'
    }
    
    // 获取通知标签类型
    const getNoticeTagType = (type) => {
      const typeMap = {
        system: 'danger',
        order: 'success',
        custom: 'warning',
        appointment: 'info'
      }
      return typeMap[type] || ''
    }
    
    // 帮助和反馈
    const showHelpDialog = ref(false)
    const showFeedbackDialog = ref(false)
    const feedbackForm = reactive({
      type: '',
      content: '',
      contact: ''
    })
    
    // 反馈表单验证规则
    const feedbackRules = {
      type: [
        { required: true, message: '请选择反馈类型', trigger: 'change' }
      ],
      content: [
        { required: true, message: '请输入反馈内容', trigger: 'blur' },
        { min: 10, max: 500, message: '反馈内容长度应在10-500个字符之间', trigger: 'blur' }
      ]
    }
    
    // 打开帮助对话框
    const openHelpDialog = () => {
      showHelpDialog.value = true
    }
    
    // 打开反馈对话框
    const openFeedbackDialog = () => {
      showFeedbackDialog.value = true
    }
    
    // 提交反馈
    const submitFeedback = async () => {
      const valid = await feedbackFormRef.value.validate().catch(() => false)
      if (!valid) return
      
      // 模拟提交反馈
      setTimeout(() => {
        ElMessage.success('感谢您的反馈，我们会尽快处理！')
        showFeedbackDialog.value = false
        // 重置表单
        feedbackForm.type = ''
        feedbackForm.content = ''
        feedbackForm.contact = ''
      }, 1000)
    }
    
    // 用户菜单操作
    const handleCommand = (command) => {
      switch (command) {
        case 'profile':
          router.push('/user')
          break
        case 'settings':
          router.push('/user/settings')
          break
        case 'logout':
          ElMessageBox.confirm('确认退出系统吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            // 清除登录信息
            localStorage.removeItem('token')
            localStorage.removeItem('username')
            localStorage.removeItem('userRole')
            localStorage.removeItem('userAvatar')
            router.push('/login')
          }).catch(() => {})
          break
      }
    }
    
    // 当前激活的菜单项
    const activeMenu = computed(() => {
      const { path } = route
      return path
    })
    
    // 需要保持活跃的页面
    const keepAlivePages = ['Home', 'CustomList', 'DesignWorks']
    
    // Logo URL
    const logoUrl = ref('') // 实际使用时应该设置真实的Logo URL
    
    // 初始化
    onMounted(() => {
      fetchNotices()
    })
    
    return {
      sidebarCollapsed,
      toggleSidebar,
      activeMenu,
      username,
      userRole,
      userAvatar,
      defaultAvatar,
      showNoticeDrawer,
      activeNoticeTab,
      unreadNotices,
      allNotices,
      hasNotice,
      readNotice,
      getNoticeTypeText,
      getNoticeTagType,
      showHelpDialog,
      showFeedbackDialog,
      feedbackForm,
      feedbackFormRef,
      feedbackRules,
      openHelpDialog,
      openFeedbackDialog,
      submitFeedback,
      handleCommand,
      keepAlivePages,
      logoUrl,
      isDarkMode,
      toggleTheme
    }
  }
}
</script>

<style scoped>
.layout-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏 */
.header-container {
  height: var(--layout-header-height);
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 16px;
  background-color: var(--component-background);
  box-shadow: 0 1px 4px var(--shadow-color);
  z-index: 10;
  position: relative;
}

.header-left {
  display: flex;
  align-items: center;
}

.logo-container {
  display: flex;
  align-items: center;
  margin-right: 24px;
}

.logo-img {
  height: 32px;
  margin-right: 8px;
}

.logo-text {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  color: var(--heading-color);
}

.toggle-sidebar {
  font-size: 20px;
  cursor: pointer;
  margin-right: 16px;
  color: var(--text-color-secondary);
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.theme-switch {
  cursor: pointer;
  font-size: 20px;
  color: var(--text-color-secondary);
}

.notice-badge {
  margin-right: 8px;
}

.notice-icon {
  font-size: 20px;
  cursor: pointer;
  color: var(--text-color-secondary);
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.username {
  margin: 0 8px;
  color: var(--text-color);
}

/* 主内容区域 */
.main-container {
  display: flex;
  flex: 1;
  overflow: hidden;
}

/* 侧边栏 */
.sidebar-container {
  width: var(--layout-sider-width);
  height: 100%;
  background-color: var(--component-background);
  border-right: 1px solid var(--border-color);
  transition: width var(--transition-time);
  display: flex;
  flex-direction: column;
  position: relative;
  z-index: 9;
}

.sidebar-container.collapsed {
  width: 64px;
}

.sidebar-menu {
  border-right: none;
  background-color: transparent;
}

.sidebar-menu:not(.el-menu--collapse) {
  width: var(--layout-sider-width);
}

.sidebar-footer {
  padding: 16px;
  border-top: 1px solid var(--border-color);
  margin-top: auto;
}

.footer-links {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.footer-links a {
  color: var(--text-color-secondary);
  font-size: 12px;
}

.version-info {
  font-size: 12px;
  color: var(--text-color-secondary);
  text-align: center;
}

/* 内容区域 */
.content-container {
  flex: 1;
  height: 100%;
  overflow: hidden;
  background-color: var(--background-color);
}

.content-wrapper {
  padding: 16px;
  min-height: 100%;
}

/* 通知样式 */
.notice-container {
  padding: 0 10px;
}

.notice-list {
  margin-top: 10px;
}

.notice-item {
  padding: 12px;
  margin-bottom: 12px;
  border-radius: 4px;
  background-color: var(--component-background);
  box-shadow: 0 1px 2px var(--shadow-color);
  cursor: pointer;
  transition: background-color 0.3s, transform 0.3s;
}

.notice-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px var(--shadow-color);
}

.notice-item.read {
  opacity: 0.7;
}

.notice-title {
  display: flex;
  align-items: center;
  margin-bottom: 6px;
}

.notice-title span {
  margin-left: 8px;
  font-weight: 500;
}

.notice-content {
  margin-bottom: 6px;
  font-size: 14px;
  color: var(--text-color);
}

.notice-time {
  font-size: 12px;
  color: var(--text-color-secondary);
  text-align: right;
}

.empty-notice {
  padding: 20px 0;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .header-container {
    padding: 0 12px;
  }
  
  .logo-text {
    display: none;
  }
  
  .username {
    display: none;
  }
  
  .header-right {
    gap: 12px;
  }
  
  .sidebar-container {
    position: fixed;
    top: var(--layout-header-height);
    left: 0;
    height: calc(100% - var(--layout-header-height));
    transform: translateX(-100%);
    transition: transform var(--transition-time);
    z-index: 999;
    box-shadow: 2px 0 8px var(--shadow-color);
  }
  
  .sidebar-container:not(.collapsed) {
    transform: translateX(0);
  }
  
  .content-wrapper {
    padding: 12px;
  }
}
</style> 